package com.hxzy.config.inteceptor;

import cn.hutool.core.util.StrUtil;
import com.hxzy.common.constans.MarketingConstans;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.*;
import com.hxzy.controller.vue.login.resp.AdminLoginResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author wy
 * @Description 后台令牌拦截器
 * @Date 2023/8/29 16:58
 * @Version 1.0
 */
@Component
public class AdminTokenValidateHandlerInterceptor implements HandlerInterceptor {

    /**
     * 一个用户可以登录多次
     */
    @Autowired
    private MultipleTokenService multipleTokenService;

    /**
     * 一个用户只允许登录一次
     */
    @Autowired
    private UniqueTokenService uniqueTokenService;

    /**
     * 单次登录还是多次登录
     */
    @Value(value = "${token.unique}")
    private boolean tokenUnique;

    /**
     * 是否为要令牌续时
     */
    @Value(value = "${token.duration}")
    private boolean duration;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取令牌
        String jwtToken=request.getHeader(MarketingConstans.ADMIN_HEADER);

        if(StrUtil.isBlank(jwtToken)){
            ServletUtil.outJson(response, AckCode.TOKEN_NOT_BLANK);
            return false;
        }

        AdminLoginResp adminLoginResp=null;
        //多态
        JwtTokenService<AdminLoginResp>  tokenService=null;
        if(tokenUnique){
            tokenService=this.uniqueTokenService;
            adminLoginResp=tokenService.getLoginResp(jwtToken);
        }else{
            tokenService=this.multipleTokenService;
            adminLoginResp=tokenService.getLoginResp(jwtToken);
        }

        if(adminLoginResp==null){
            ServletUtil.outJson(response,AckCode.APPLE_EXPIRED);
            return false;
        }

        //要不要开启续时功能
        if(duration){
            tokenService.verifyToken(adminLoginResp);
        }

        //存储到本地线程，供后面的使用
        MarketingThreadLocalUtil.adminThreadLocal.set(adminLoginResp);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        MarketingThreadLocalUtil.adminThreadLocal.remove();
    }
}
